gcapp.set "messageVisible","false"

gcapp.get doc,frontDocument
doc.get parent,"parentStructure"

! Read paste board
ReadPasteboard pb

! Copies source will have "Sources" in itmem 0
! and have at least 2 items
#pbType="?"
ifDef pb
  if @pb.count>1
    pb.0.get "#pbType"
    ifNDef #pbType
      #pbType="?"
    endif
  endif
endif

! clipboard does not have copied sources
if #pbType!="Sources"
  beep
  #msg=local("No sources found on the clipboard")
  #msg2=local("Copy sources first and then paste them")
  UserOption "#var",#msg,#msg2,local("OK")
  exit
endif

! check if they have details
#hasDetails="false"
Repeat "#i",1,@pb.count-1
  pb.#i.get slink
  if @slink.count>1
    #hasDetails="true"
    break
  endif
EndRepeat

! see if details are wanted
if #hasDetails
  #cancel=local("Cancel")
  #msg=local("Do you want to paste source details with source links?")
  #msg2=local("You can edit details after pasting by clicking the 'info' icons.")
  UserOption "#var",#msg,#msg2,local("With Details"),#cancel,local("Without Details")
  if #var=#cancel
    exit
  endif
  if #var=local("Without Details")
    #hasDetails="false"
  endif
endif

! paste each source
doc.beginUndo
Repeat "#i",1,@pb.count-1
  ! it will be list of GEDDOM lines
  pb.#i.get slink
  
  ! first line is level, "SOUR", "ID"
  slink.0.get sourLine
  parent.addStructure sblock,@sourLine.1,@sourLine.2
  
  if #hasDetails="true" && @slink.count>1
    ! shift from copied levels to pasted levels
    #shift=@sourLine.0-@parent.level-1
    Repeat "#j",1,@slink.count-1
      slink.#j.get sourLine
      if @sourLine.0-#shift<@sblock.level+1
        ! back up to structure one level lower
        Repeat
          sblock.get sblock,"parentStructure"
          if @sourLine.0-#shift=@sblock.level+1
            break
          endif
        EndRepeat
      else if @sourLine.0-#shift>@sblock.level+1
        ! should never happen, just ignore this line
        continue
      endif
      
      ! add line and set sblock to the new structure
      sblock.addStructure sblock,@sourLine.1,@sourLine.2
    EndRepeat
  endif
EndRepeat
doc.endUndo local("Paste Sources")
